package com.ello.base.utils

import java.io.BufferedOutputStream
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
import java.nio.charset.Charset

/**
 * @author du_xi
 * @date   2023/6/6
 */
object IOUtils {
    /**
     * 输入流读取为字符串
     */
    fun InputStream.readString(charset: Charset = Charsets.UTF_8): String {
        return kotlin.runCatching {
            use { inputStream ->
                val os = ByteArrayOutputStream()
                val b = ByteArray(8192)
                var len: Int
                while (inputStream.read(b, 0, 8192).also { len = it } != -1) {
                    os.write(b, 0, len)
                }
                val byteArray = os.toByteArray()
                String(byteArray, charset)
            }
        }.getOrDefault("")
    }

    /**
     * 写入文件
     */
    fun InputStream.writeToFile(destFile: File): Boolean {
        return kotlin.runCatching {
            use {
                val outputStream =
                    BufferedOutputStream(FileOutputStream(destFile))
                copyTo(outputStream)
                outputStream.flush()
            }
            true
        }.getOrDefault(false)

    }
}